<?php
/*
 * kernel/object.log.php
 *
 * This code is distributed and used under the GNU GPL v2 License,
 * please, read file LICENSE, which is situated in root directory,
 * or in "LICENSE" directory with most acceptable translation for you
 *
 * Logging events, actions, etc.
 *
 * Copyright (C) 2010, Taras Kudla
 *
 */
define("_MAX_FILE_SIZE",1048576);
define("_MAX_DB_RECORDS",1000);
define("_AUTH_LOG","auth.log");
define("_SYS_LOG","sys.log");
define("_ERROR_LOG","error.log");

class gLog extends gKernel {
	
    private $logTable="log";
    private $logFile=_SYS_LOG;
    private $MAXPERLIFE=100;
    private $CALLEDFILE=0;
	
    public function init(){
    }

    /**
     * Returns log message level by number
     *
     * @param constant $level
     * @return string
     */
    public function GetLevel($levelno){
        switch($levelno){
            case _LOG_MESSAGE: return "MESSAGE";break;
            case _LOG_NOTICE: return "NOTICE ";break;
            case _LOG_ERROR: return "ERROR  ";break;
            case _LOG_CRITICAL: return "CRITICAL";break;
            default: return "UNKNOWN";
        }
    }

    /**
     * Writes log message
     *
     * @param string    $message    Log message text
     * @param constant  $level      Log message level
     * @param constant  $file       Log message file where to write
     * @param string    $name       Log message source name
     * @return boolean
     */
    public function write($message,$level=_LOG_MESSAGE,$file=_SYS_LOG,$name=null) {
        if($name==null){
            //$name=($this->core->ENV_LAYER==_ENV_KERNEL?"KERNEL":strtolower($this->core->ENV_CALLER["MOD"])."-".strtolower($this->core->ENV_CALLER["NAME"]));
        }
        $remoteAddr = isset($_SERVER["REMOTE_ADDR"])?$_SERVER["REMOTE_ADDR"]:"unknown";
        list($name,$level,$ip)=$this->core->escapeList($name,$level,$remoteAddr);
        $date=date("Y-m-d H:i:s");
        if($this->core->get("logtofile")==YES){
            $this->WriteToFile($name,$message,$file,$level);
        }
        return true;
    }

    /**
     * Writes log message directly to file
     *
     * @param string    $from       Log message source name
     * @param string    $message    Log message text
     * @param constant  $filetype   Type of message
     * @param constant  $level      Message level
     * @return <type>
     */
    public function WriteToFile($from,$message,$filetype=_SYS_LOG,$level=_LOG_MESSAGE){
        $this->CheckForArchiving($filetype);
        $remoteAddr = isset($_SERVER["REMOTE_ADDR"])?$this->core->escapeString($_SERVER["REMOTE_ADDR"]):"unknown";
        $line=date("M j H:i:s ").$remoteAddr." ".$this->GetLevel($level)." ".(  $this->core->isloaded("user")?$this->core->user->GetUserFingerprint():null)." ".$from.": ".$message."\r\n";
        $logsfile = $this->core->parseasdir($this->core->get("logsdir"));
        $file=$logsfile.$filetype;
        if( !is_writable($file) ){
            $this->core->error("LOG"," Cannot create/open log file ($file). Please create it and|or change permissions.",_ERR_FATAL,__FILE__,__LINE__);
            return false;
        } else {
            $f=fopen($file,"a+");
            fwrite($f,$line);
            fclose($f);
         return true;
        }
    }

    /**
     * Checks whether log file need to archived
     *
     * @param constant $filetype    Log message file
     * @return boolean
     */
    private function CheckForArchiving($filetype=_SYS_LOG){
        $dir = $this->core->parseasdir($this->core->get("logsdir"));
        $file = $dir.$filetype;
        if(file_exists($file) && filesize($file) > _MAX_FILE_SIZE){
            if(!is_writable($dir)){
                $this->core->error("LOG","Directory is not writable. Cannot write to log archives",_ERR_FATAL,__FILE__,__LINE__);
                return false;
            }
            if(extension_loaded("zlib")){
                $in = fopen($file,"r");
                $out= fopen($file.".".date("U").".gz","w+");
                while(!feof($in)){
                    $buffer = fread($in,4096);
                    fwrite($out,gzencode($buffer,9));
                }
                fclose($in);
                fclose($out);
                $clean=fopen($file,"w+");
                fwrite($clean,null);
                fclose($clean);
            } else {
                copy($file,$file.".".date("U")."log");
            }
            return true;
        }
        return false;
    }
	
	
    public function export(){
        
    }
	
}